<template>
	<view class="full-container">
		<custom-nav
			:title="
				(mode === 'preview' ? '预览-' : '') + formTitle.slice(0, 10)
			"
		></custom-nav>
		<view
			class="form-container"
			:style="{ paddingBottom: mode === 'add' ? '120rpx' : '180rpx' }"
		>
			<view class="top-tips" v-if="processFormId && mode !== 'edit'">
				提示:【{{ formName }}】表单关联审批流程【{{
					processName
				}}】，提交后将自动发起审批
			</view>
			<view :class="'forms-wrap ' + (formDisabled ? 'disabled' : '')">
				<uni-forms ref="form">
					<uni-forms-item
						v-for="(item, index) in labelItems"
						:key="index"
					>
						<view
							:class="
								'title' + (item.required ? ' required' : '')
							"
							>{{ item.label }}</view
						>
						<template v-if="item.type === 'INPUT'">
							<uni-easyinput
								class="uni-mt-5"
								trim="all"
								autoHeight
								:maxlength="getInputMaxLength(item)"
								:disabled="formDisabled"
								:placeholder="item.placeholder"
								:value="dataCollection[item.formItemId]"
								@input="
									onInputDataChange(index, $event, 'INPUT')
								"
							></uni-easyinput>
						</template>
						<template v-if="item.type === 'SELECT'">
							<uni-data-select
								:value="dataCollection[item.formItemId]"
								:placeholder="item.placeholder"
								:localdata="
									getSelectMenu(item.scheme, formDisabled)
								"
								@input="
									onInputDataChange(index, $event, 'SELECT')
								"
							></uni-data-select>
						</template>
						<template v-if="item.type === 'DATE'">
							<uni-datetime-picker
								type="date"
								return-type="date"
								:value="dataCollection[item.formItemId]"
								:disabled="formDisabled"
								@change="
									onInputDataChange(index, $event, 'DATE')
								"
							/>
						</template>
						<template v-if="item.type === 'CASCADER'">
							<view class="picker-wrap">
								<uni-data-picker
									:ref="'provincePicker' + index"
									:value="dataCollection[item.formItemId]"
									:localdata="getAddressMap()"
									popup-title="请选择省市区"
									@change="
										onInputDataChange(
											index,
											$event,
											'CASCADER'
										)
									"
								></uni-data-picker>
								<view
									class="picker-mask"
									v-if="formDisabled"
								></view>
							</view>
							<!-- ss: {{item.formItemId}} : {{dataCollection[item.formItemId]}}-->
							<!-- <uni-easyinput :value="dataCollection[item.formItemId]" :placeholder="item.placeholder" :disabled="formDisabled" readonly @tap="showProvincePicker(index)"/>				 -->
						</template>
						<view class="error-tips">{{
							errorTipsCollection[item.formItemId] || ''
						}}</view>
					</uni-forms-item>
				</uni-forms>
			</view>
		</view>
		<!-- <uni-data-picker ref="provincePicker"
		:value="dataCollection[item.formItemId]" 
		:localdata="getAddressMap()" 
		popup-title="请选择省市区"
		></uni-data-picker> -->
		<view>
			<view v-if="mode === 'edit'" class="bottom-button-bd edit">
				<view class="ml20 mr20">
					<button
						:class="modifiable ? '' : 'disabled'"
						class="primary-button"
						@tap.stop="handlerOnModify"
					>
						修改
					</button>
				</view>
				<view class="df flex-between mt20 ml20 mr20">
					<button
						:class="1 ? '' : 'disabled'"
						class="sc-button"
						@tap.stop="handlerCheckFile"
					>
						查看文件
					</button>
					<button
						:class="
							processInstanceId
								? 'sc-button'
								: 'sc-button disabled'
						"
						@tap.stop="handlerCheckAboutForm"
					>
						查看审批单{{ processInstanceId }}
					</button>
				</view>
			</view>
			<view v-if="mode === 'add'" class="bottom-button-bd add">
				<view class="ml20 mr20">
					<button class="primary-button" @tap.stop="handlerOnSubmit">
						提交
					</button>
				</view>
			</view>
			<view v-if="mode === 'preview'" class="bottom-button-bd add">
				<view class="df flex-between mt20 ml20 mr20">
					<button class="sc-button primary" @tap.stop="handlerShare">
						分享
					</button>
					<button class="sc-button" @tap.stop="handleStartFill">
						开始填写
					</button>
				</view>
			</view>
		</view>

		<uni-popup ref="popup" type="bottom">
			<view class="pop-body-wrap">
				<view class="pop-title">分享</view>
				<!-- <uni-list>
					<uni-list-item  showExtraIcon :extra-icon="{type: 'weixin', size: 30, color: '#1AAD19'}" link  clickable title="分享给微信好友"  open-type="share" @click="sharePage">
						111
					</uni-list-item>
					<uni-list-item  showExtraIcon :extra-icon="{type: 'image', size: 30,}" link clickable title="保存二维码图片" ></uni-list-item>
					<uni-list-item  showExtraIcon  :extra-icon="{type: 'link', size: 30,}" link clickable title="复制链接" ></uni-list-item>
				</uni-list> -->
				<view class="pop-menu-list">
					<button class="item" open-type="share" data-id="1">
						<uni-icons type="weixin" size="30" color="#1AAD19">
						</uni-icons
						>分享给微信好友<uni-icons
							type="right"
							size="20"
							class="icon-right"
						/>
					</button>
					<button class="item" data-id="2" @click="canvasCode">
						<uni-icons type="image" size="30"></uni-icons
						>保存二维码图片<uni-icons
							type="right"
							size="20"
							class="icon-right"
						/>
					</button>
					<!-- <button class="item"><uni-icons type="link" size="30"></uni-icons>复制链接<uni-icons type="right" size="20" class="icon-right" /></button> -->
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="popupSelectRecord" type="bottom">
			<view class="pop-body-wrap">
				<view class="pop-title">请选择要修改的记录</view>
				<view class="select-pop-list-wrap">
					<view class="select-pop-list">
						<view
							v-for="(item, index) in popSelectDataList"
							:key="index"
							class="pt20 pb20 pl20 pr20 mt20 mb20 ml20 mr20 backf"
							@click="clickOnPopupToChangeRecordItem(item)"
						>
							<view class="df flex-between mb-20">
								<view class="g3 fwb f30 record-title">{{
									item.name
								}}</view>
								<view class="primary-color f30">选择></view>
							</view>
							<view class="mt10 info-color f24"
								>关联审批流程:
								{{ item.processName || '-' }}</view
							>
							<view class="mt10 info-color f24"
								>审批流程状态:
								{{ item.processStatusName || '-' }}</view
							>
							<view class="mt10 info-color f24"
								>提交时间:
								{{ item.submitTime.replace('T', ' ') }}</view
							>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<view style="opacity: 0">
			<canvas
				id="qrcode"
				canvas-id="qrcode"
				style="
					width: 200px;
					height: 200px;
					position: fixed;
					z-index: -1;
					top: -2000px;
					left: -2000px;
					visibility: hidden;
					opacity: 0;
				"
			></canvas>
		</view>
	</view>
</template>

<script>
/*
	   支持三种模式
	   preview: 预览
	   add: 添加
	   edit: 编辑
	*/
import dayjs from '@/common/dayjs.min.js'
import UQRCode from 'uqrcodejs'
import { getAccountInfoSync } from '@/common/base.js'
import { getAddressData } from '../../utils/pca'
import { getPropertyData } from '../../utils/index'
import { previewFile } from '@/common/utils.js'

export default {
	components: {},
	data() {
		return {
			markJumpLogin: false,
			mode: '', // 模式: add: 本人填写 	edit: 编辑 	preview:预览页面
			sync: '0', // edit模式下是否同步formkey数据
			editMode: false, // 是否进入修改模式
			modifiable: false, // 数据是否可以修改
			formDisabled: true, // 是否禁用这个表单输入
			recordId: '', // 记录id
			formId: '', // 表单id
			formTitle: '', //标题
			formKey: '', // 表单key
			formVersion: '', // 表单version
			formName: '', // 表单名称
			processName: '', // 关联的审批流程名称
			processInstanceId: '', // 关联的审批流程实例id
			processFormId: '', // 关联的审批流程form id
			processNodeId: '', // 关联的审批流程 nodeId
			fileUrl: '', // 文件列表
			labelItems: [],
			dataCollection: {},
			errorTipsCollection: {},
			popSelectDataList: [],
			formData: {},
		}
	},
	onLoad(options) {
		this.init(options)
	},
	onShow() {
		const token = uni.getStorageSync('token')
		const phoneNumberCode = uni.getStorageSync('phoneNumberCode')
		if (!(token && phoneNumberCode)) {
			this.markJumpLogin = true
			uni.navigateTo({
				url: '/subPackagesForm/pages/authorization/index',
			})
		} else {
			if (this.markJumpLogin) {
				const pages = getCurrentPages()
				this.init(pages[pages.length - 1].options)
			}
			this.markJumpLogin = false
		}
	},
	onShareAppMessage(data) {
		const id = data.target.dataset.id
		if (id === '1') {
			//
			return {
				title: '邀请您填写表单~',
				imageUrl:
					'https://oss-pub.fosun-creative.com/staticfile/mini-program/his/img/noData.png',
				path: `/subPackagesForm/pages/fillData/index?mode=preview&formKey=${this.formKey}`,
			}
		}
	},
	methods: {
		init(options) {
			const q = options.q
			let query = options
			if (q) {
				const url = decodeURIComponent(q)
				const paramsStr = url.split('?')[1] || ''
				let _params = paramsStr.split('&')
				let obj = {}
				for (let i = 0; i < _params.length; i++) {
					let arr_params = _params[i].split('=')
					obj[arr_params[0]] = arr_params[1]
				}
				query = {
					...query,
					...obj,
				}
			}
			// formKey表示表单id, id表示填写记录的id
			this.mode = query.mode || 'preview'
			this.formId = query.id
			this.formKey = query.formKey
			if (this.mode === 'edit') {
				if (query.sync) {
					this.getFormDetail(query.formKey, (data) => {
						this.getRecordData(
							query.id,
							query.formKey,
							data ? data.items : []
						)
					})
				} else {
					this.getRecordData(query.id, query.formKey)
				}
			} else {
				this.getData(query.id, query.formKey)
			}
		},
		getFormDetail(key, cb) {
			this.$request
				.request('wflow/wflow/doc/get', {
					data: {
						formKey: key,
					},
				})
				.then((res) => {
					if (res.status === 200) {
						this.formData = res.data
						cb(res.data)
						return
					}
					cb({})
				})
				.catch(() => {
					cb({})
				})
		},
		getRecordData(id, key, formKeyItems) {
			this.$request
				.request('wflow/wflow/doc/get-record', {
					data: {
						formKey: key,
						id,
					},
				})
				.then((res) => {
					if (res.status === 200) {
						if (!res.data) {
							uni.showModal({
								title: '提示信息',
								content: '表单信息不存在, 请返回重试',
								showCancel: false,
							})
							return
						}
						const data = res.data || {}

						const {
							name,
							recordId,
							processInstanceId,
							fileUrl,
							formKey,
							version,
							processFormId,
							processName,
							processNodeId,
							modifiable,
							items = [],
							data: dataGet,
						} = data
						this.recordId = id
						this.formName = name
						this.formTitle = '修改-' + this.formName
						this.formKey = formKey
						this.formVersion = version
						this.modifiable = modifiable
						this.formDisabled = !modifiable
						const renderItem = formKeyItems ? formKeyItems : items
						this.labelItems = renderItem
						this.processInstanceId = processInstanceId
						this.processFormId = processFormId
						this.processNodeId = processNodeId
						this.processName = processName
						this.fileUrl = fileUrl
						let comonbineData = {}
						Object.keys(renderItem).forEach((item) => {
							comonbineData[renderItem[item].formItemId] =
								dataGet[renderItem[item].formItemId] || ''
						})
						// 	console.log('comonbineData:', comonbineData)
						this.dataCollection = this.formatDateCollection(
							comonbineData,
							renderItem,
							'update'
						)
						this.errorTipsCollection = JSON.parse(
							JSON.stringify(this.dataCollection)
						)
						Object.keys(this.errorTipsCollection).forEach(
							(item) => {
								this.errorTipsCollection[item] = ''
							}
						)
						//console.log('dataGet:', dataGet)

						// renderItem.map(item => ({id: item.formItemId, label: item.label}))
						//console.log('dataCollection:', this.dataCollection)
						//console.log('renderItem:', renderItem.map(item => ({id: item.formItemId, label: item.label})))

						// console.log('dataCollection1', dataGet, this.dataCollection)
						// console.log('errorTipsCollection1', this.errorTipsCollection)
					}
				})
		},
		formatDateCollection(dataOrigin = {}, dataSchemas, mode = 'init') {
			let data = Object.assign(dataOrigin)
			if (mode === 'init') {
				dataSchemas.forEach((item) => {
					if (item) {
						if (item.type === 'CASCADER') {
							data[item.formItemId] = []
						} else {
							data[item.formItemId] = ''
						}
					}
				})
				console.log('data.ttt', data)
			} else {
				Object.keys(dataOrigin).forEach((key) => {
					const dSchema = dataSchemas.find(
						(item) => item.formItemId === key
					)
					if (dSchema) {
						if (dSchema.type === 'DATE') {
							data[key] = dayjs(dataOrigin[key]).format(
								'YYYY-MM-DD'
							)
						}
					}
				})
			}
			return data
		},
		getData(id, key) {
			// 查询表单详情
			this.$request
				.request('wflow/wflow/doc/get', {
					data: {
						formKey: key,
					},
				})
				.then((res) => {
					if (res.status === 200) {
						if (!res.data) {
							uni.showModal({
								title: '提示信息',
								content: '表单信息不存在, 请返回重试',
								showCancel: false,
							})
							return
						}
						const data = res.data || {}
						const {
							name,
							processFormId,
							processName,
							formKey,
							version,
							processInstanceId,
							modifiable,
							enable,
							writable,
							writableInH5,
							fileUrl,
							items = [],
							data: dataGet,
						} = data
						this.formName = name
						this.modifiable = true
						this.editMode = true
						this.formDisabled = this.mode === 'preview'

						this.labelItems = items
						this.formTitle = '填写-' + this.formName
						this.writableInH5 = writableInH5
						this.formKey = formKey
						this.formVersion = version
						// this.processInstanceId = processInstanceId;
						this.processFormId = processFormId
						// this.processNodeId = processNodeId;
						this.processName = processName
						this.fileUrl = fileUrl
						// if(!enable){
						// 	uni.showToast({
						// 		title: '当前表单禁用',
						// 		icon: 'none'
						// 	})
						// 	return
						// }
						// if(!writable){
						// 	uni.showToast({
						// 		title: '当前表单无法重复填写',
						// 		icon: 'none'
						// 	})
						// 	return
						// }
						this.dataCollection = this.formatDateCollection(
							dataGet,
							items,
							'init'
						)
						this.errorTipsCollection = JSON.parse(
							JSON.stringify(this.dataCollection)
						)

						// console.log('dataCollection2', dataGet, this.dataCollection)
						// this.modifiable = modifiable
						// if(records.length < 10){
						// 	this.pageNoMore1 = true
						// }
						// this.currentPage1 = page
						// this.dataAllformList = this.dataAllformList.concat(records)
					}
				})
		},
		getAddressMap() {
			return getAddressData()
		},
		getSelectMenu(scheme, disable) {
			if (!scheme || !scheme.options || !Array.isArray(scheme.options)) {
				return []
			}
			return scheme.options
				.filter((item) => !!item)
				.map((item) => {
					return {
						value: item.value,
						text: item.label,
						disable,
					}
				})
		},
		// showProvincePicker(index){
		// 	if(this.formDisabled){
		// 		return
		// 	}
		// 	this.$refs['provincePicker' + index].show()
		// },
		handlerShare() {
			this.$refs.popup.open()
		},
		canvasCode() {
			// todo
			const currentEnv = getAccountInfoSync().miniProgram.envVersion
			const basePath =
				currentEnv === 'release'
					? 'https://yilife.cn/inviteFillSmartForm_fill'
					: 'https://yilife.cn/inviteFillSmartForm_vFill'
			const urlPath = basePath + '?mode=preview&formKey=' + this.formKey // TODO
			uni.showLoading({
				title: '生成二维码中',
				mask: true,
			})

			const qr = new UQRCode()
			// 设置二维码内容
			qr.data = urlPath
			// 设置二维码大小，必须与canvas设置的宽高一致
			qr.size = 200
			// 调用制作二维码方法
			qr.make()
			// 获取canvas上下文
			var canvasContext = uni.createCanvasContext('qrcode', this) // 如果是组件，this必须传入
			// 设置uQRCode实例的canvas上下文
			qr.canvasContext = canvasContext
			// 调用绘制方法将二维码图案绘制到canvas上
			qr.drawCanvas()
			setTimeout(() => {
				uni.canvasToTempFilePath({
					canvasId: 'qrcode',
					fileType: 'png',
					width: qr.size,
					height: qr.size,
					success: (res) => {
						uni.hideLoading()
						console.log(res)
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: (res) => {
								uni.showToast({
									title: '保存成功',
									icon: 'none',
								})
							},
							fail: (err) => {
								console.log('err', err)
								uni.showToast({
									title: '保存失败',
									icon: 'none',
								})
							},
						})
					},
					fail: (err) => {
						console.log('err', err)
						uni.showToast({
							title: '图片生成失败',
							icon: 'none',
						})
					},
				})
			}, 300)
		},
		handlerCheckFile() {
			if (!this.fileUrl) {
				uni.showToast({
					title: '当前文件不存在',
					icon: 'none',
				})
				return
			}
			// todo展示文件
			previewFile(this.fileUrl)
		},
		handlerCheckAboutForm() {
			if (!this.processInstanceId) {
				uni.showToast({
					title: '表单未关联审批流程',
					icon: 'none',
				})
				return
			}
			uni.navigateTo({
				url: `/subPackagesIndex/pages/index/approval/mainSub/approvalDetail?instanceId=${
					this.processInstanceId
				}&nodeId=${
					this.processNodeId ? this.processNodeId : 'undefined'
				}&type=2&formId=${this.processFormId}`,
			})
		},
		generateJumpData(data) {
			uni.setStorageSync('_associateFormData', {
				title: this.formName,
				data: Object.keys(this.dataCollection).map((item, index) => {
					const findIndex = this.labelItems.findIndex(
						(s) => s.formItemId === item
					)
					const find = this.labelItems[findIndex]
					const type = find ? find.type : ''
					let value = this.dataCollection[item]
					if (type === 'DATE') {
						value = dayjs(value).format('YYYY-MM-DD')
					}
					return {
						index: findIndex,
						key: find ? find.label : item,
						value,
					}
				}),
				resource: data.resource,
				transientId: data.transientId,
			})
		},
		handlerOnSubmit() {
			if (this.validateForm()) {
				uni.showToast({
					title: '请检查参数',
					icon: 'none',
				})
				return
			}
			this.$request
				.request('wflow/wflow/doc/get', {
					data: {
						formKey: this.formKey,
					},
				})
				.then((resT) => {
					if (!resT.data.writableInH5) {
						uni.showToast({
							title: '请到电脑端提交',
							icon: 'none',
						})
						return
					}
					this.$request
						.request('wflow/wflow/doc/submit-record', {
							data: {
								formKey: this.formKey,
								version: this.formVersion,
								data: this.dataCollection,
							},
							isReject: false,
							method: 'post',
						})
						.then((res) => {
							if (res.status === 200) {
								const data = res.data || {}
								uni.showToast({
									title: '提交成功',
									icon: 'none',
								})
								if (!this.processFormId) {
									setTimeout(() => {
										uni.reLaunch({
											url: `/subPackagesForm/pages/index/index?tab=2`,
										})
									}, 500)
									return
								}
								if (data.transientId) {
									this.generateJumpData(data)
									// 跳转到
									uni.redirectTo({
										url: `/subPackagesIndex/pages/index/approval/launch/launchApproval?code=${data.processFormId}&isAssociateForm=true`,
									})
								}
							} else if (res.status === 501) {
								uni.showModal({
									title: '提示信息',
									content: res.message,
									showCancel: false,
									confirmText: '刷新数据',
									success: (res) => {
										const pages = getCurrentPages() // 获取栈实例
										const currentPage =
											pages[pages.length - 1] //当前页面路径(带参数)
										const options = currentPage.options
										const optionsString = Object.keys(
											options
										)
											.map(
												(item) =>
													`${item}=${options[item]}`
											)
											.join('&')
										const path = currentPage.route
										const currentFullPage =
											pages[pages.length - 1]['$page'][
												'fullPath'
											] //当前页面路径(带参数)

										const comPath =
											'/' +
											path +
											'?' +
											optionsString +
											'&sync=1'
										console.log(
											'currentFullPage: ',
											currentFullPage
										)
										console.log('tpath: ', comPath)
										uni.redirectTo({
											url: comPath,
										})
									},
								})
							}
						})
				})
		},
		sharePage() {},
		onEducationChange() {
			//
		},
		onGenderChange() {},
		calculateWordLength(word) {
			let count = 0
			word.split('').forEach((char) => {
				if (/^[\u4e00-\u9fa5]+$/.test(char)) {
					// 汉字占两个字符
					count += 2
				}
				count++
			})
			return count
		},
		getInputMaxLength(item) {
			return getPropertyData(item, '.scheme.fontConfig.maxLength') || 200
		},
		onInputDataChange(index, value, type) {
			const item = this.labelItems[index]
			const keyiId = item.formItemId
			const originValue = this.dataCollection[item.formItemId]
			console.log('index', index, 'value', value, 'type', type)
			if (type === 'INPUT') {
				this.$set(this.dataCollection, keyiId, value)
				// 限制maxlength
				this.validateFormItem(keyiId, index)
			} else if (type === 'SELECT') {
				this.$set(this.dataCollection, keyiId, value)
				if (!originValue && value) {
					this.validateFormItem(keyiId, index)
				}
			} else if (type === 'DATE') {
				this.$set(
					this.dataCollection,
					keyiId,
					value ? dayjs(value).format('YYYY-MM-DD') : ''
				)
				if (!originValue && value) {
					this.validateFormItem(keyiId, index)
				}
			} else if (type === 'CASCADER') {
				const { value: valueGet } = value.detail || {}
				// console.log('ss', valueGet.map(item => item.value))
				this.$set(
					this.dataCollection,
					keyiId,
					valueGet.map((item) => item.value)
				)
				if (!originValue && value) {
					this.validateFormItem(keyiId, index)
				}
			}
		},
		validateFormItem(i, index) {
			let matched = false
			const itemData = this.labelItems[index]
			console.log('ppt:', i, index, this.dataCollection[i], itemData)
			if (!this.dataCollection[i] && itemData.required === true) {
				console.log('ppt2: error', itemData.placeholder)
				this.$set(
					this.errorTipsCollection,
					i,
					'*' + itemData.placeholder
				)
				matched = true
			} else {
				const pattern = getPropertyData(
					itemData,
					'.scheme.fontConfig.pattern'
				)
				const patternTips = getPropertyData(
					itemData,
					'.scheme.fontConfig.tips'
				)
				const reg = pattern
					? new RegExp(pattern.replace(/^\//, '').replace(/\/$/, ''))
					: new RegExp()
				// console.log('regregregreg:', reg, this.errorTipsCollection[i], reg.test(this.errorTipsCollection[i]))
				if (
					pattern &&
					patternTips &&
					!reg.test(this.dataCollection[i])
				) {
					this.$set(this.errorTipsCollection, i, '*' + patternTips)
					matched = true
				} else {
					this.$set(this.errorTipsCollection, i, '')
				}
			}
			return matched
		},
		validateForm() {
			Object.keys(this.errorTipsCollection).forEach(
				(key) => (this.errorTipsCollection[key] = '')
			) // 清空
			let matchedCount = 0
			const keys = Object.keys(this.dataCollection)
			for (let i = 0; i < keys.length; ++i) {
				const findIndex = this.labelItems.findIndex(
					(t) => t.formItemId === keys[i]
				)
				if (this.validateFormItem(keys[i], findIndex)) {
					matchedCount++
				}
			}
			return matchedCount > 0
		},
		handleClearFill() {
			Object.keys(this.dataCollection).forEach((item) => {
				this.$set(this.dataCollection, item, '')
			})
			// this.$set(this.dataCollection, 0, '1233'pl30 pr30 pt20 pb50)
		},
		handleEditData() {
			const ret = this.validateForm()
			if (!ret) {
				uni.showToast({
					title: '请检查输入参数',
					icon: 'none',
				})
				return
			}
			console.log('dddd2', this.dataCollection)
		},
		handleStartFill() {
			// 先判断是否可以填写
			this.$request
				.request('wflow/wflow/doc/get', {
					data: {
						formKey: this.formKey,
					},
				})
				.then((res) => {
					if (!res || !res.data) {
						return
					}
					const { writableInH5, writable, once, modifiable } =
						res.data
					if (!writableInH5) {
						// h5可以重新填写
						uni.showToast({
							title: '请在电脑端发起',
							icon: 'none',
						})
					} else if (writable === true) {
						// 可以填写, 表示未填写或者可填写多次
						if (once) {
							// 只能能填写一次
							this.formDisabled = false
							this.mode = 'add'
							return
						} else {
							// 可以填写多次, 需要查询下记录
							this.popupSelectRecord(this.formKey, () => {
								if (this.popSelectDataList.length === 0) {
									// 无记录, 直接填写
									this.formDisabled = false
									this.mode = 'add'
									return
								} else {
									//  有记录提示是重新写还是修改
									uni.showModal({
										title: '提示',
										content:
											'当前表单已提交过，请选择修改填写记录或重新填写',
										showCancel: true,
										confirmText: '修改记录',
										cancelText: '重新填写',
										success: (res3) => {
											if (res3.confirm) {
												this.$refs.popupSelectRecord.open()
											} else {
												this.formDisabled = false
												this.mode = 'add'
											}
										},
									})
								}
							})
						}
					} else {
						// 不可以填写(不满足可以填写的条件)
						if (modifiable === true) {
							// 不可填写, 但是可修改(可重新提交)
							this.popupSelectRecord(this.formKey, () => {
								if (this.popSelectDataList.length === 0) {
									uni.showToast({
										title: '查找记录失败',
										icon: 'none',
									})
									return
								}
								uni.showModal({
									title: '提示',
									content: `当前表单已提交过，请选择${
										once
											? '重新填写'
											: '修改填写记录或重新填写'
									}`,
									showCancel: true,
									confirmText: '修改记录',
									cancelText: once ? '放弃' : '重新填写',
									success: (res3) => {
										if (res3.confirm) {
											this.$refs.popupSelectRecord.open()
										} else {
											if (once) {
												return
											}
											this.formDisabled = false
											this.mode = 'add'
										}
									},
								})
							})
						} else {
							uni.showModal({
								title: '提示',
								content: once
									? '当前表单只允许填写一次'
									: '当前表单只不允许修改',
								confirmText: '确定',
								showCancel: false,
							})
						}
					}
				})

			// 带入数据
			// this.$set(this.dataCollection, 0, '1233')
		},
		handlerOnModify() {
			if (!this.modifiable) {
				uni.showToast({
					title: '当前表单不允许修改',
					icon: 'none',
				})
				return
			}
			if (this.validateForm()) {
				uni.showToast({
					title: '请检查输入参数',
					icon: 'none',
				})
				return
			}
			this.$request
				.request('wflow/wflow/doc/get', {
					data: {
						formKey: this.formKey,
					},
				})
				.then((resT) => {
					if (!resT.data.writableInH5) {
						uni.showToast({
							title: '请到电脑端提交',
							icon: 'none',
						})
						return
					}
					this.$request
						.request('wflow/wflow/doc/submit-record', {
							data: {
								updateRecordId: this.recordId,
								formKey: this.formKey,
								version: this.formVersion,
								data: this.dataCollection,
							},
							isReject: false,
							method: 'post',
						})
						.then((res) => {
							if (res.status === 501) {
								uni.showModal({
									title: '提示信息',
									content: res.message,
									showCancel: false,
									confirmText: '刷新数据',
									success: (res) => {
										const pages = getCurrentPages() // 获取栈实例
										const currentPage =
											pages[pages.length - 1] //当前页面路径(带参数)
										const options = currentPage.options
										const optionsString = Object.keys(
											options
										)
											.map(
												(item) =>
													`${item}=${options[item]}`
											)
											.join('&')
										const path = currentPage.route
										const currentFullPage =
											pages[pages.length - 1]['$page'][
												'fullPath'
											] //当前页面路径(带参数)

										const comPath =
											'/' +
											path +
											'?' +
											optionsString +
											'&sync=1'
										console.log(
											'currentFullPage: ',
											currentFullPage
										)
										console.log('tpath: ', comPath)
										uni.redirectTo({
											url: comPath,
										})
									},
								})
								return
							}
							const data = res.data || {}
							uni.showToast({
								title: '修改成功',
								icon: 'none',
							})
							if (data.transientId) {
								this.generateJumpData(data)
								// 跳转到
								uni.redirectTo({
									url: `/subPackagesIndex/pages/index/approval/launch/launchApproval?code=${data.processFormId}&isAssociateForm=true`,
								})
							} else {
								setTimeout(() => {
									uni.reLaunch({
										url: `/subPackagesForm/pages/index/index?tab=2`,
									})
								}, 500)
							}
						})
				})
		},
		popupSelectRecord(formKeyIn, cb) {
			// 先请求
			this.$request
				.request('wflow/wflow/doc/get-record-h5-page', {
					data: {
						formKey: formKeyIn,
						page: 1,
						pageSize: 100,
					},
					method: 'post',
				})
				.then((res) => {
					if (res.status === 200) {
						this.popSelectDataList = (
							res.data.records || []
						).filter((item) => item.modifiable)
						// if(isOnce && this.popSelectDataList.length === 1){ // 确实只有一条记录
						// 	this.clickOnPopupToChangeRecordItem(this.popSelectDataList[0])
						// 	return
						// }
					} else {
						this.popSelectDataList = []
					}
					cb()
					// this.$refs.popupSelectRecord.open()
				})
				.catch((res) => {
					this.popSelectDataList = []
					cb()
				})
			//popSelectDataList
		},
		clickOnPopupToChangeRecordItem(item) {
			this.$refs.popupSelectRecord.close()
			uni.redirectTo({
				url: `/subPackagesForm/pages/fillData/index?mode=edit&id=${item.recordId}&formKey=${item.formKey}`,
			})
		},
	},
}
</script>

<style lang="scss">
.full-container {
	min-height: 100vh;
	background-color: #fff;
	.title {
		padding-bottom: 20rpx;
		&.required::before {
			content: '*';
			color: red;
			margin-right: 4rpx;
		}
	}
}
.form-container {
	padding: 20rpx 30rpx 120rpx;
}
.top-tips {
	padding: 20rpx;
	background-color: #f4fbfb;
	margin-bottom: 30rpx;
	font-size: 28rpx;
}
.bottom-button-bd {
	display: block;
	.primary-button {
		&.disabled {
			background: #eaeaea;
			border-color: #eaeaea;
			color: #fff;
		}
	}
	&.edit {
		height: 170rpx;
	}
	z-index: 1;
	.sc-button {
		width: 48%;
		border-radius: 200px;
		background-color: transparent;
		border: 1px solid #2d94ff;
		padding: 0;
		margin: 0;
		font-size: 28rpx;
		height: 80rpx;
		line-height: 80rpx;
		color: #2d94ff;
		&.primary {
			border-color: #b7daff;
			color: #fff;
			margin: 0;
			padding: 0;
			background: linear-gradient(155deg, #2d94ff 1%, #b7daff 100%);
		}
		&::after {
			display: none;
		}
		&.disabled {
			background-color: #eaeaea;
			border-color: #eaeaea;
			color: #fff;
		}
	}
}
.forms-wrap {
	&.disabled {
		.uni-date,
		.uni-data-tree-input,
		.uni-select {
			background-color: #f6f6f7;
		}
	}
	.error-tips {
		color: red;
		font-size: 28rpx;
		line-height: 1;
		height: 28rpx;
		padding-top: 10rpx;
	}
}
.uni-forms .uni-forms-item {
	margin-bottom: 10rpx;
}
.pop-body-wrap {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	overflow: hidden;
}
.pop-title {
	height: 100rpx;
	line-height: 100rpx;
	text-align: center;
	font-size: 32rpx;
	color: #333;
	text-align: center;
	background: #fff;
	border-bottom: 1px solid #eaeaea;
	border-radius: 20rpx 20rpx 0 0;
	background: linear-gradient(
		89.89deg,
		#e3edff -0.1%,
		rgba(223, 234, 255, 0) 100.6%
	);
}
.pop-menu-list {
	background-color: #fff;
	button::after {
		border: none;
	}
	.item {
		.uni-icons {
			margin-right: 10rpx;
		}
		display: flex;
		align-items: center;
		padding: 25rpx 30rpx;
		line-height: 1;
		font-size: 28rpx;
		background-color: #fff;
		color: #666;
		border-bottom: 1px solid #f5f6f7;
		&:last-child {
			border-bottom: none;
		}
		.icon-right {
			margin-left: auto;
		}
	}
}
.select-pop-list-wrap {
	min-height: 400rpx;
	max-height: 800rpx;
	overflow-y: auto;
	background-color: #eaeaea;
}
.select-pop-list {
	.item {
		padding: 10rpx;
		margin: 10rpx 0;
		border-radius: 8px;
		background-color: #fff;
	}
}
.picker-wrap {
	position: relative;
	.picker-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 9999;
	}
}
</style>
